<template>
    <div class="business">
        <el-container>
            <el-header class="header">
              出差申请
              &emsp;
              <el-icon color="#fb9337" size="20px"><Opportunity /></el-icon>
              &emsp;
              <el-icon color="#acb5c1" size="20px"><Umbrella /></el-icon>
              &emsp;
              <el-icon color="#acb5c1" size="20px"><MoreFilled /></el-icon>
              </el-header>
            <el-main>
                <!-- 操作按钮 -->
                <div class="btns">
                    <el-button type="warning" @click="showDialog">发起新的</el-button>
                    &emsp;
                    <el-upload :headers="headers" name="excel" :show-file-list="false" :data="{userid:formData.userid}" accept=".xlsx" :on-change="clickchange" :disabled="boolean" :on-error="error" :on-success="success"
                        action="/api/business/import">
                        <el-button :loading="boolean">导入</el-button>
                    </el-upload>
                    &emsp;
                    <el-button>
                        <el-link :href="'/api/business/download?userid='+formData.userid" target="_blank">导出</el-link>
                    </el-button>
                    <el-tabs v-model="activeName" class="tabs" @tab-change="handleClick">
                        <el-tab-pane label="待办事项" name="1"></el-tab-pane>
                        <el-tab-pane label="已办事项" name="2"></el-tab-pane>
                        <el-tab-pane label="抄送事项" name="3"></el-tab-pane>
                        <el-tab-pane label="我发起的" name="4"></el-tab-pane>
                        <el-tab-pane label="全部数据" name="5"></el-tab-pane>
                        <el-tab-pane label="概览" name="6"></el-tab-pane>
                        <el-tab-pane label="统计报表" name="7"></el-tab-pane>
                    </el-tabs>
                </div>
                <!-- 表格 -->
                <el-table :data="tableData" style="width: 100%">
                    <el-table-column prop="_id" label="编号" show-overflow-tooltip  />
                    <el-table-column prop="status" label="当前流程" :formatter="formatterStatus"/>
                    <el-table-column prop="name" label="申请人"  />
                    <el-table-column prop="reason" label="出差事由" width="200px" />
                    <el-table-column prop="starttime" label="出发日期" :formatter="formatterTime" width="150px" />
                    <el-table-column prop="endtime" label="返回日期" :formatter="formatterTime" width="150px" />
                    <el-table-column prop="days" label="出差总天数" width="150px"  />
                    <el-table-column label="操作" width="100px" >
                        <template #default="scope">
                            <el-button link type="primary" size="small"
                            @click.prevent="editRow(scope)"
                            >
                            编辑
                            </el-button>
                            <el-button link type="primary" size="small"
                            @click.prevent="deleteRow(scope)"
                            >
                            删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <el-pagination class="pagination" background layout="prev, pager, next" :total="total" @current-change="handleCurrentChange" />

                <!-- 抽屉 -->
                <el-drawer
                    ref="drawerRef"
                    v-model="addDialog"
                    title="出差申请"
                    direction="rtl"
                    custom-class="demo-drawer"
                >
                    <div class="demo-drawer__content">
                        <!-- 新增表单 -->
                        <el-form :model="formData" label-position="top" :rules="rules" ref="formRef">
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="申请人" prop="name" >
                                        <el-input v-model="formData.name" disabled />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="所在部门" >
                                        <el-input v-model="formData.dept" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="24">
                                    <el-form-item label="出差事由说明" prop="reason" >
                                        <el-input type="textarea" v-model="formData.reason" placeholder="输入内容" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="出发日期" prop="starttime" >
                                        <el-date-picker
                                            v-model="formData.starttime"
                                            type="date"
                                            placeholder="选择一个出发日期"
                                        />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="返回日期" prop="endtime" >
                                        <el-date-picker
                                            v-model="formData.endtime"
                                            type="date"
                                            placeholder="选择一个出发日期"
                                        />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="24">
                                    <el-form-item label="出差总天数" prop="days" >
                                        <el-input v-model="formData.days"  />
                                    </el-form-item>
                                </el-col>
                               
                            </el-row>
                        </el-form>

                        <div class="demo-drawer__footer">
                            <el-button @click="addDialog = false">取消</el-button>
                            <el-button type="primary" @click="onSubmit(formRef)">提交申请</el-button>
                        </div>
                    </div>
                </el-drawer>
                
            </el-main>
        </el-container>
    </div>
</template>

<script setup>

import { ref,onMounted,reactive } from "vue";
import { business_list , business_add ,business_delete } from '../../api'
import { ElNotification } from 'element-plus'

let boolean = ref(false)
let headers = ref({Authorization:'Bearer' + ' ' + localStorage.getItem('token')})
let activeName = ref('');
let tableData = ref([]);
let total = ref(0);
let addDialog = ref(false);
let formData = ref({ 
    userid: JSON.parse( localStorage.getItem('userinfo') )._id,
    name: JSON.parse( localStorage.getItem('userinfo') ).name ,
    reason:'',
    starttime:'',
    endtime:'',
    days:'' 
});
let formRef = ref();
//文件状态改变时触发
let clickchange = (uploadFile)=>{
    console.log(uploadFile)
    if(uploadFile.percentage < 100)
    boolean.value = true
}
//文件上传成功时触发
let success = ()=>{
    boolean.value = false
     ElNotification({ //弹出通知
          title: '导入通知',
          message: '导入成功',
          type: 'success',
    })
}
//文件上传失败时触发
let error = ()=>{
    boolean.value = false
     ElNotification({ //弹出通知
          title: '导入通知',
          message: '导入失败',
          type: 'error',
    })
}
//验证 申请人
const validateName = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入申请人'))
    } else {
        callback()
    }
}
//验证 出差事由
const validateReason = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入出差事由'))
    } else {
        callback()
    }
}
//验证 出发日期
const validateStarttime = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请选择一个出发日期'))
    } else {
        if( new Date(formData.value.starttime) - new Date(formData.value.endtime) > 0 ){//返回日期必须大于出发日期
            formData.value.starttime = '';
            formData.value.days = '';
            callback(new Error('出发日期必须早于返回日期!'))
        }else if( formData.value.starttime && formData.value.endtime  ) { //出发日期,返回日期都存在, 计算总天数
            formData.value.days = (new Date(formData.value.endtime) - new Date(formData.value.starttime) ) / (24 * 60 * 60 * 1000)
        }
        callback()
    }
}
//验证 返回日期
const validateEndtime = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请选择一个返回日期'))
    } else {
        
        if( new Date(formData.value.starttime) - new Date(formData.value.endtime) > 0 ){//返回日期必须大于出发日期
            formData.value.endtime = '';
            formData.value.days = '';
            callback(new Error('返回日期必须大于出发日期!'))
        }else if( formData.value.starttime && formData.value.endtime  ) { //出发日期,返回日期都存在, 计算总天数
            formData.value.days = (new Date(formData.value.endtime) - new Date(formData.value.starttime) ) / (24 * 60 * 60 * 1000)
        }
        callback()
    }
}
//验证 出差总天数
const validateDays = (rule, value, callback) => {
    if (value === '' || Number(value) == 0) {
        callback(new Error('请填写正确的总天数'))
    } else {
        callback()
    }
}

//表单的验证规则 rules
const rules = reactive({
  name: [{ validator: validateName, trigger: 'blur',required: true, }],
  reason: [{ validator: validateReason, trigger: 'blur',required: true, }],
  starttime: [{ validator: validateStarttime, trigger: 'blur',required: true, }],
  endtime: [{ validator: validateEndtime, trigger: 'blur',required: true, }],
  days: [{ validator: validateDays, trigger: 'blur',required: true, }],
})

//新增
let showDialog = ()=>{
    addDialog.value = true
    formData.value = { 
    userid: JSON.parse( localStorage.getItem('userinfo') )._id,
    name: JSON.parse( localStorage.getItem('userinfo') ).name ,
    reason:'',
    starttime:'',
    endtime:'',
    days:'' 
}
}

//组件挂载完成时, 请求出差申请列表
onMounted( async ()=>{
    let userinfo = JSON.parse( localStorage.getItem('userinfo') );
    let res = await business_list({ userid: userinfo._id ,page:1 })
    tableData.value = res.data.list;
    total.value = res.data.total;
})

let handleClick = (name)=>{
    console.log(activeName.value,name);
}
//格式化 流程状态
let formatterStatus = function(row, column, cellValue, index){
    return cellValue == 0 ? '审核中' : '已通过';
}
//补零
let addZero = (num)=>{
    return num<10 ? '0'+num : num;
}
//格式化时间
let formatterTime = function(row, column, cellValue, index){
    let d = new Date(cellValue);
    return `${d.getFullYear()}-${addZero( d.getMonth()+1 )}-${ addZero( d.getDate() ) }`;
}
//分页
let handleCurrentChange = async (page)=>{
    //请求page对应页码的数据
    let userinfo = JSON.parse( localStorage.getItem('userinfo') );
    let res = await business_list({ userid: userinfo._id ,page })
    tableData.value = res.data.list;
}
//编辑
let editRow = (scope)=>{
    addDialog.value = true
    formData.value = JSON.parse( JSON.stringify( scope.row))
}
//删除
let deleteRow = async (scope)=>{
  let userinfo = JSON.parse( localStorage.getItem('userinfo') );
  let res = await business_delete({ userid:userinfo._id , id:scope.row._id , page:1})
  tableData.value = res.data.list
}

//提交表单
let onSubmit = (formRef)=>{
    formRef.validate( async (valid) => {
    if (valid) {
      if( formData.value._id ){
        ElNotification({ //弹出通知
              title: '编辑通知',
              message: '编辑成功',
              type: 'success',
            })
        addDialog.value = false;//关闭抽屉
      }else{
            //发请求, 新增出差申请
            let res = await business_add(formData.value);
          if( res.data.code == 200 ){ //如果服务端返回 200, 表示新增成功
            ElNotification({ //弹出通知
              title: '新增通知',
              message: res.data.msg,
              type: 'success',
            })
            addDialog.value = false;//关闭抽屉
            tableData.value = res.data.list;
            total.value = res.data.total;
            formRef.resetFields(); //重置表单
          }else{
            ElNotification({
                title: '新增通知',
                message: res.data.msg,
                type: 'error',
            })
    
          }
      }
    } else {
      return false
    }
  })
}

</script>

<style scoped lang='scss'>
.business{
    .header{
        display: flex;
        align-items: center;
        font-weight: bold;
    }
    .btns{
        display: flex;
        .tabs{
            margin-left: 30px;
        }
    }
    .pagination{
        margin: 20px 0;
    }
}
</style>